#include <glog/logging.h>
#include <QJsonDocument>

#include "entity/mqtt_entity.h"
#include "manager/json_parser.h"
#include "manager/mqtt_observer.h"
#include "manager/config_manager.h"
#include "mqtt/mqtt_client_config.h"

MqttClientConfig::MqttClientConfig(const char *id, const char *topic, const char *host, int port)
    : MqttClient(id, topic, host, port)
{

}

void MqttClientConfig::on_connect(int rc) {
    LOG(INFO) << "MqttClientConfig | on_connect | rc" << rc;
    if (rc == 0) {
        this->subscribe_topic();
    }
}

void MqttClientConfig::on_message(const struct mosquitto_message *message) {
    char *payload = (char*)message->payload;
    LOG(INFO) << "MqttClientConfig | on_message | payload" << payload;
    QJsonDocument jsonResponse = QJsonDocument::fromJson(payload);
    if (jsonResponse.isEmpty() == true) {
        LOG(INFO) << "MqttClientConfig | on_message | payload is not json object";
        return;
    }
    ConfigEntity config = JsonParser::parse_config(jsonResponse.object());
    LOG(INFO) << "MqttClientConfig | on_message | time_cycle" << config.time_cycle <<
                ", picture_format" << config.picture_format.toStdString() <<
                ", video_resolution" << config.video_resolution.toStdString();

    // update ecb config
    ConfigEntity *ecb_config = ConfigManager::getInstance()->get_ecb_config();
    ecb_config->time_cycle = config.time_cycle;
    ecb_config->picture_format = config.picture_format;
    ecb_config->video_resolution = config.video_resolution;
    ConfigManager::getInstance()->save();

    MqttObserver::get_instance()->notify_config(config);
}

void MqttClientConfig::on_subscribe(int mid, int qos_count, const int *granted_qos) {
    LOG(INFO) << "MqttClientConfig | on_subscribe Success";
}
